﻿using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Timers;
using System.Web.Http;
using System.Web.Http.Filters;
using System.Web.Mvc;
using static System.Collections.Specialized.BitVector32;

namespace YunShop_WebAPI.API
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        /// <summary>
        /// 初始化
        /// </summary>
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            //路由配置
            Register(GlobalConfiguration.Configuration);
            //异常处理
            GlobalConfiguration.Configuration.Filters.Add(new APIExceptionFilterAttribute());

            //#region 自动处理一些问题
            //var ContributionTimer = new Timer
            //{
            //    Interval = 1 * (5 * 60 * 1000),
            //    AutoReset = true,
            //    Enabled = true
            //};
            //ContributionTimer.Elapsed += new ElapsedEventHandler(delegate { GetContribution(); });
            //ContributionTimer.Start();
            //void GetContribution()
            //{
            //    new Action(delegate { }).BeginInvoke(delegate
            //    {
            //        try
            //        {
            //            YunShop_WebAPI.BLL.Utils.Write_Log(Model.Log_File.Warning, "初始化数据：" + DateTime.Now.ToString());
            //            BLL.WebOrderCommon.AutomaticSettlement(sql_connection);
            //        }
            //        catch (Exception ex)
            //        {
            //            YunShop_WebAPI.BLL.Utils.Write_Log(Model.Log_File.Warning, "初始化出现异常：" + ex.ToString());
            //            throw ex;
            //        }
            //    }, null);
            //}
            //#endregion

        }

        //protected void Application_End(object sender, EventArgs e)
        //{
        //    //下面的代码是关键，可解决IIS应用程序池自动回收的问题   
        //    System.Threading.Thread.Sleep(1000);
        //    string url = "http://yl.klwl.net/#/login";
        //    HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        //    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
        //    Stream receiveStream = myHttpWebResponse.GetResponseStream();//得到回写的字节流  
        //}

        /// <summary>
        /// 跨域设置
        /// </summary>
        protected void Application_BeginRequest()
        {
            if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
            {
                Response.End();
            }
        }

        /// <summary>
        /// 路由配置
        /// </summary>
        protected void Register(HttpConfiguration configuration)
        {
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();


            configuration.Routes.MapHttpRoute(
            name: "Default",
            routeTemplate: "{controller}/{action}"
            //defaults: new { /*id = RouteParameter.Optional*/ }
            );


            configuration.Routes.MapHttpRoute(
                 name: "Default2",
                 routeTemplate: "{controller}/{id}/{action}",
                 defaults: new { id = RouteParameter.Optional });

        }

        /*      /// <summary>
              /// 路由配置
              /// </summary>
              protected void Register2(HttpConfiguration configuration)
              {
                  GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
                  configuration.Routes.MapHttpRoute(
                  name: "Default2",
                  routeTemplate: "{controller}/{id}/{action}",
                  defaults: new { controller = "mall", id = UrlParameter.Optional, action = "CallBack" });
              }*/
    }

    /// <summary>
    /// 异常消息拦截
    /// </summary>
    public class APIExceptionFilterAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// 异常处理
        /// </summary>
        public override void OnException(HttpActionExecutedContext context)
        {
            StringBuilder message = new StringBuilder();
            message.Append(context.Exception.Message + "\r\n");
            message.Append(context.Exception.StackTrace.Replace("\r\n--- 引发异常的上一位置中堆栈跟踪的末尾 ---", "").Trim());
            base.OnException(context);
        }
    }
}
